﻿using System;
using System.Xml.Linq;
using BattleFury.Lib.Extensions;
using BattleFury.Lib.Input;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace BattleFury.Lib.Controls
{
	public class ImageButton
		: Control
	{
        //private string _state = "Button";
		private bool _isHighlighted;
		private bool _isClicked;

		private Texture2D _imageSource;
		private Texture2D _highlightedImageSource;
		private Texture2D _clickedImageSource;

		public string ImageSource { get; set; }
		public string HighlightedImageSource { get; set; }
		public string ClickedImageSource { get; set; }
		public Action OnClick { get; set; }

		public override void Deserialize(XElement element, object callingObject)
		{
			base.Deserialize(element, callingObject);

			ImageSource = element.GetString("ImageSource");
			HighlightedImageSource = element.GetString("HighlightedImageSource");
			ClickedImageSource = element.GetString("ClickedImageSource");

			if (!string.IsNullOrEmpty(ImageSource)) _imageSource = RenderEngine.Get().Content.Load<Texture2D>(ImageSource);
			if (!string.IsNullOrEmpty(HighlightedImageSource)) _highlightedImageSource = RenderEngine.Get().Content.Load<Texture2D>(HighlightedImageSource);
			if (!string.IsNullOrEmpty(ClickedImageSource)) _clickedImageSource = RenderEngine.Get().Content.Load<Texture2D>(ClickedImageSource);

			var onClick = element.GetString("OnClick", string.Empty);
			if (!string.IsNullOrEmpty(onClick) && callingObject != null)
			{
				var split = onClick.Split('.');
				var methodName = split[split.Length - 1];
				var callingType = callingObject.GetType();
				var method = callingType.GetMethod(methodName);
				OnClick = () => method.Invoke(callingObject, new object[] { });
			}
		}

		public override void Update(GameTime gameTime)
		{
			_isHighlighted = false;
			_isClicked = false;

			if (Input.Mouse.CurrentBounds.Intersects(Bounds))
			{
				_isHighlighted = true;
				if (Input.Mouse.IsMouseButtonHeld(MouseButtons.Left))
				{
					_isClicked = true;
				}
				if (Input.Mouse.IsMouseButtonPressed(MouseButtons.Left))
				{
					if (OnClick != null) OnClick();
				}
			}
		}

		public override void Draw(GameTime gameTime)
		{
			var leftBounds = new Rectangle((int)Position.X, (int)Position.Y, (int)Size.X, (int)Size.Y);

			var texture = _imageSource;
			if (_isHighlighted) texture = _highlightedImageSource;
			if (_isClicked) texture = _clickedImageSource;

			SpriteBatch.Draw(texture, leftBounds, Tint);
		}
	}
}